package com.example.huangliting.experimentalarrangementsystem.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.activity.AddLessonActivity;
import com.example.huangliting.experimentalarrangementsystem.adapter.LinearLayoutBaseAdapter;
import com.example.huangliting.experimentalarrangementsystem.bean.PersonClass;
import com.example.huangliting.experimentalarrangementsystem.util.DateUitls;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.view.LinearLayoutForListView;
import com.haozhang.lib.SlantedTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HuangLiting on 2018/3/15.
 */

public class HomePageFragment extends Fragment {

    public HomePageFragment() {
        // Required empty public constructor
    }

    private final String getPersonClassUrl = HttpUtils.headerUrl+"/timetable/getPersonClass";
    private SharedPreferences sp;
    private TextView classPoint_tv;
    private List<PersonClass> dataList;
    private TextView today_tv;
    private boolean isGetData = false;

    private JSONArray datalistJson;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_home_page, container, false);
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);
        classPoint_tv = contentView.findViewById(R.id.classPoint);
        today_tv = contentView.findViewById(R.id.todayTime);
        sp = getActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        today_tv.setText(DateFormat.format("yyyy年MM月dd日", new Date()).toString() + " " + DateUitls.formateDay(cal.get(Calendar.DAY_OF_WEEK)));
        /*dataList = new ArrayList<>();
        if(sp.getBoolean("isLogin",false)){
            Map<String, String> params = new HashMap<String, String>();
            params.put("tid",sp.getString("userId",""));
            initDataByPost(params,"utf-8");
        } else
            classPoint_tv.setText("未登录，请先登录");*/


       /* forListView.setOnItemClickListener(new LinearLayoutForListView.OnItemClickListener() {
            @Override
            public void onItemClicked(View v, Object obj, int position) {
                if (position == list.size() -1) {
                    list.add("aaaaaaaaaaa");
                    adapter.notifyDataSetChanged();
                }
            }
        });
*/
        return contentView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.main_menu_item, menu);
    }

    //private List<PersonClass> list;


    Handler getClassHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                datalistJson = jsonObj.getJSONArray("timetables");
                if (datalistJson!=null){
                    for (int i = 0; i < datalistJson.length(); i++) {
                        PersonClass personClass = new PersonClass();
                        JSONObject jsonObject = datalistJson.getJSONObject(i);
                        personClass.setClassId(jsonObject.getInt("cid"));
                        personClass.setClassName(jsonObject.getString("lessonName"));
                        personClass.setStartClassNum(jsonObject.getInt("classNum"));
                        personClass.setEndClassNum(jsonObject.getInt("classNum")+jsonObject.getInt("classLength")-1);
                        personClass.setLroom(jsonObject.getString("lname"));
                        dataList.add(personClass);
                    }
                }
                final MyAdapter adapter = new MyAdapter(getView().getContext(), dataList);
                final LinearLayoutForListView forListView = (LinearLayoutForListView) getView().findViewById(R.id.ll_list);
                forListView.setAdapter(adapter);
                classPoint_tv.setText("今天有"+dataList.size()+"个课程信息");

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    private void initDataByPost(final Map<String, String> params, final String encode){

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(getPersonClassUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = getClassHandler.obtainMessage();
                        msg.obj = text;
                        getClassHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    class MyAdapter extends LinearLayoutBaseAdapter {
        public MyAdapter(Context context, List<PersonClass> list) {
            super(context, list);
        }
        @Override
        public View getView(int position) {
            View view = getLayoutInflater().inflate(R.layout.item, null);
            TextView classNum_tv = (TextView) view.findViewById(R.id.lessonNum);
            TextView className_tv = (TextView) view.findViewById(R.id.className_tv_index);
            TextView lRoom_tv = (TextView) view.findViewById(R.id.lroom_tv_index);
            classNum_tv.setText(getItem(position).getStartClassNum()+"-"+getItem(position).getEndClassNum()+"节");
            className_tv.setText(getItem(position).getClassName());
            lRoom_tv.setText(getItem(position).getLroom());

            return view;
        }

    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        //   进入当前Fragment
        if (enter && !isGetData) {
            isGetData = true;
            //   这里可以做网络请求或者需要的数据刷新操作
            if(sp.getBoolean("isLogin",false)){
                dataList = new ArrayList<>();
                Map<String, String> params = new HashMap<String, String>();
                params.put("tid",sp.getString("userId",""));
                initDataByPost(params,"utf-8");
            } else
                classPoint_tv.setText("未登录，请先登录");

        } else {
            isGetData = false;
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onPause() {
        super.onPause();
        isGetData = false;
    }


}
